/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * gui.java
 *
 * Created on 15-02-2012, 17:48:49
 */
package GUI;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import project_temple.client.clientHandler;
import project_temple.utilityclient.weathercurrent;
import project_temple.utilityclient.weatherforecast;

/**
 *
 * @author STARTHERE
 */
public class gui extends javax.swing.JFrame {

    private String text;

    /** Creates new form gui */
    public gui() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel(){
            public void paintComponent(Graphics g)
            {
                Dimension d = getSize();
                g.drawImage(this.getToolkit().getImage(getClass().getResource("/images/1.jpg")), 0, 0, d.width, d.height, null);
                setOpaque( false );
                super.paintComponent(g);
            }
        };
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("weather client gui");
        setIconImage(this.getToolkit().getImage(getClass().getResource("/images/1.jpg")));

        jPanel1.setMinimumSize(new java.awt.Dimension(800, 600));
        jPanel1.setPreferredSize(new java.awt.Dimension(800, 600));
        jPanel1.setRequestFocusEnabled(false);
        jPanel1.setVerifyInputWhenFocusTarget(false);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/Search.png"))); // NOI18N
        jButton1.setBorder(null);
        jButton1.setBorderPainted(false);
        jButton1.setHideActionText(true);
        jButton1.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jButton1.setBorderPainted(false);
        jButton1.setContentAreaFilled(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField1.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jTextField1.setForeground(Color.BLUE);
        jTextField1.setText("Enter your location");
        jTextField1.setOpaque(false);
        jTextField1.setToolTipText("");
        jTextField1.setBorder(null);
        jTextField1.setCaretColor(new java.awt.Color(204, 255, 0));
        jTextField1.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        jTextField1.setMargin(new java.awt.Insets(1, 2, 2, 2));
        jTextField1.setSelectedTextColor(new java.awt.Color(0, 0, 255));
        jTextField1.setVerifyInputWhenFocusTarget(false);
        jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                chuotclick(evt);
            }
        });
        jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                rakhoitf(evt);
            }
        });

        jLabel1.setMaximumSize(new java.awt.Dimension(175, 120));
        jLabel1.setMinimumSize(new java.awt.Dimension(175, 120));
        jLabel1.setOpaque(false);
        jLabel1.setPreferredSize(new java.awt.Dimension(175, 120));

        jLabel2.setOpaque(false);
        jLabel2.setForeground(Color.GREEN);

        jLabel3.setOpaque(false);
        jLabel3.setForeground(Color.GREEN);

        jLabel4.setOpaque(false);
        jLabel4.setForeground(Color.GREEN);

        jLabel5.setOpaque(false);
        jLabel5.setForeground(Color.GREEN);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(457, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(10, 10, 10)
                                .addComponent(jButton1))
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(10, 10, 10)
                        .addComponent(jLabel2)
                        .addGap(7, 7, 7)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)))
                .addGap(18, 18, 18)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel9)
                .addContainerGap(444, Short.MAX_VALUE))
        );

        jLabel1.getAccessibleContext().setAccessibleName("currentweather");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
//        jLabel1.setIcon(new ImageIcon(getToolkit().getImage(getClass().getResource("/icon/comay.png"))));
        Socket socket;
        try {
            socket = new Socket("localhost", 1111);
            clientHandler cl = new clientHandler(socket, text);
            cl.start();
            String weather = cl.receive();
            weathercurrent wt = process(weather);
            jLabel2.setText("Temperature  :" + wt.getTemperature());
            jLabel3.setText("Humidity  :" + wt.getHumidity());
            jLabel4.setText("Wind  :" + wt.getWind());
            jLabel5.setText("Condition  :" + wt.getCodition());
            jLabel1.setIcon(new ImageIcon(getToolkit().getImage(getClass().getResource("/icon/" + wt.getCodition() + ".png"))));
            System.out.print(weather);
            List<weatherforecast> forecast = processforecast(weather);
            jLabel6.setText(forecast.get(0).toString());
            jLabel7.setText(forecast.get(1).toString());
            jLabel8.setText(forecast.get(2).toString());
            jLabel9.setText(forecast.get(3).toString());
            System.out.println(forecast.get(0).getCodition());
            System.out.println(forecast.get(1).getCodition());
            System.out.println(forecast.get(2).getCodition());
            System.out.println(forecast.get(3).getCodition());
        } catch (IOException ex) {
            Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    private weathercurrent process(String st) {
        weathercurrent weather = new weathercurrent();
        StringBuilder sb = new StringBuilder();
        char c;
        int i;
        int len = st.length();
        for (i = 0; i < len; i++) {
            if ((c = st.charAt(i)) != '\n') {
                sb.append(c);
            } else {//lay duoc dong curent
                String wt = sb.toString().trim();
                StringBuilder cr = new StringBuilder();
                for (i = 0; i < wt.length(); i++) {
                    if ((c = wt.charAt(i)) != ',') {
                        cr.append(c);
                    } else {
                        String key, data;
                        key = cr.substring(0, cr.indexOf("=")).trim();
                        data = cr.substring(cr.indexOf("=") + 1, cr.length()).trim();
                        if (key.equals("humidity")) {
                            weather.setHumidity(data);
                        } else if (key.equals("temperature")) {
                            weather.setTemperature(data);
                        } else if (key.equals("condition")) {
                            weather.setCodition(data);
                        } else if (key.equals("wind")) {
                            weather.setWind(data);
                        }
                        cr.delete(0, cr.length());
                    }
                }
                break;
            }
        }
        return weather;
    }

    private List<weatherforecast> processforecast(String stt) {
        List<weatherforecast> forecast = new ArrayList<weatherforecast>();
        String st;
        StringBuilder sc = new StringBuilder(stt);
        StringBuilder sb = new StringBuilder();
        String[] sdayofweek = {"MonDay", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        SimpleDateFormat date = new SimpleDateFormat();
        int day = date.getCalendar().get(Calendar.DAY_OF_WEEK);
        sc.delete(0, sc.indexOf(":") + 3);
        sc.append("\n");
        st = sc.toString();
        char c;
        int fc = 0;
        
        for (int i = 0; i < st.length(); i++) {
            if ((c = st.charAt(i)) != '\n') {
                sb.append(c);
            } else {
                fc++;
                weatherforecast weather = new weatherforecast();
                String wt = sb.toString().trim();
                sb.delete(0, sb.length());
                StringBuilder cr = new StringBuilder();
                for (int j = 0; j < wt.length(); j++) {
                    if ((c = wt.charAt(j)) != ',') {
                        cr.append(c);
                    } else {
                        String key, data;
                        key = cr.substring(0, cr.indexOf("=")).trim();
                        data = cr.substring(cr.indexOf("=") + 1, cr.length()).trim();
                        if (key.equals("temperature")) {
                            weather.setTemperature(data);
                        } else if (key.equals("condition")) {
                            weather.setCodition(data);
                        }
                        switch (fc) {
                            case 1:
                                weather.setDate("ToDay");
                                break;
                            case 2:
                                weather.setDate(sdayofweek[(day + 1) % 7]);
                                break;
                            case 3:
                                weather.setDate(sdayofweek[(day + 2) % 7]);
                                break;
                            case 4:
                                weather.setDate(sdayofweek[(day + 3) % 7]);
                                break;
                        }cr.delete(0, cr.length());
                    }

                }
                forecast.add(weather);
            }
        }
        return forecast;
    }
    private void chuotclick(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_chuotclick
        // TODO add your handling code here:
        jTextField1.setText(null);
    }//GEN-LAST:event_chuotclick
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void ra(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ra
        // TODO add your handling code here:
    }//GEN-LAST:event_ra

    private void rakhoitf(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_rakhoitf
        // TODO add your handling code here:
        text = jTextField1.getText();
    }//GEN-LAST:event_rakhoitf
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new gui().setVisible(true);
            }
        });


    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
